<template>
    <div class="calendar-view">
        <div class="calendar-common-img">
            <div class="calendar-common">
                <div class="calendar-common-head">
                    <div class="calendar-common-head-icon" @click="up"><i class="iconfont icon-xiangzuo"></i></div>
                    <div class="calendar-common-head-day">{{ curDate }}</div>
                    <div class="calendar-common-head-icon" @click="next"><i class="iconfont icon-xuanzeqixiayige"></i>
                    </div>
                    <div class="today" @click="today">{{i18n('backToday','回到今天')}}</div>
                </div>
                <div class="calendar-time">
                    <ul class="calendar-time-head">
                        <li v-for="(smin,index) in weekdaysMin">{{ smin }}</li>
                    </ul>
                    <ul class="calendar-time-day">
                        <li v-for="time in monthList">
                            <div @click="checkedDay(time)" class="calendar-time-day-li"
                                 :class="{'calendar-time-day-li-hover':curDateHoverMonth == time.time,'calendar-time-day-li-hover-day':curDateMonth == time.time,'day-forbid':time.month!='current'}">
                                {{ time.day }}
                                <span class="calend-span" :class="{'calend-span-hover':curDateHoverMonth == time.time}"
                                      v-if="getCalendarDayListData(time)"></span>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <!--日程数据-->
        <div class="schedule-common">
            <div class="schedule-common-head">{{ curDateHoverMonth }}{{i18n('meeting','会议')}}</div>
            <div class="schedule-common-head-button-day">
                <div class="schedule-common-head-button" @click="addRow"><i class="iconfont icon-add"></i></div>
            </div>
            <div style="margin-top: 1rem;margin-left: .2rem" v-if="dayData && dayData.length>0">
                <div class="schedule-common-list" v-for="(obj,index) in dayData" @click="calendarButtom(obj)"
                     :key="index">
                    <div class="schedule-common-list-node"><span></span></div>
                    <div class="schedule-common-list-time">{{i18n('meetingTime','会议时间')}}：{{ obj.start }}<span
                        v-if="obj.end">-{{ obj.end }}</span></div>
                    <div class="schedule-common-list-common">
                        <div>{{ obj.title }}</div>
                    </div>
                </div>
            </div>
        </div>
        <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
            <ul class="mask-bottom">
                <li v-for="(list,index) in buttonsRow" :key="index" @click="handButtonClick(list)">{{
                        list.btnLabel
                    }}
                </li>
            </ul>
        </uni-popup>
        <uni-popup ref="popupRow" type="bottom" border-radius="10px 10px 0 0">
            <ul class="mask-bottom">
                <li v-for="(list,index) in buttonsHead" :key="index" @click="handButtonClick(list)">{{
                        list.btnLabel
                    }}
                </li>
            </ul>
        </uni-popup>
    </div>
</template>

<script>
import moment from "moment";
import MainLayoutApi from "@/api/MainLayout/MainLayoutApi";
import FormBoListApi from "@/api/FormBoList/FormBoListApi";

/**
 * 日历组件
 */
export default {
    name: "CalendarView",
    data() {
        return {
            //当前月数据
            monthData: [],
            //当月全量数据(未重构)
            allMonthData: [],
            //当前日详细数据
            dayData: [],
            calendarView: "",
            //当前年月
            curYearAndMonth: "",
            //当前日期 年月日
            curDate: "",
            curDateMonth: '',
            curDateHoverMonth: '',//选中的那天时间
            format: "YYYY-MM-DD HH:mm:ss",
            weekdaysMin: [this.i18n('one','一'), this.i18n('two','二'),this.i18n('three','三'),this.i18n('wanton','四'),this.i18n('five','五'), this.i18n('land','六'),this.i18n('sun','日')],
            //日历数据
            monthList: [],
            idField: "",
            //按钮
            buttonsRow: [],
            buttonsHead: [],
            curRow: {},
            jsScript: '',
        }
    },
    props: {
        config: {}
    },
    created() {
        this.loadData()
        //初始化日历
        this.curDate = moment().format("YYYY-MM");
        this.curDateMonth = moment().format("YYYY-MM-DD");
        this.curDateHoverMonth = moment().format("YYYY-MM-DD")
        this.init();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formCustomViewLang",key);
        },
        init() {
            this.monthList = [];
            var currentDate = moment(this.curDate);
            //获取月份第一天星期几.0是星期日改成7
            var startOfDay = moment(currentDate).startOf('month').day();
            if (startOfDay == 0) {
                startOfDay = 7;
            }
            //获取上一个多少天
            var precedingMonth = moment(currentDate).subtract(1, 'month').daysInMonth();
            //计算这个月要显示上个月的月份数据
            if (startOfDay > 1) {
                let preceding = precedingMonth - startOfDay + 1;
                var precedingDay = moment(currentDate).subtract(1, 'month').format("YYYY-MM")
                for (var j = 1; j < startOfDay; j++) {
                    preceding = preceding + 1
                    var precedingObj = {
                        time: precedingDay + '-' + preceding,
                        day: preceding,
                        month: 'preceding',
                    }
                    this.monthList.push(precedingObj)
                }
            }
            //获取当前月份天数
            var daysInMonth = moment(currentDate).daysInMonth();
            //获取这个月数据
            for (var i = 1; i <= daysInMonth; i++) {
                if (i < 10) {
                    var a = '0' + i
                } else {
                    var a = i
                }
                var day = this.curDate + '-' + a;
                var obj = {
                    time: day,
                    day: i,
                    month: 'current',
                }
                this.monthList.push(obj)
            }
            //获取下个月的数据计算这个月要展示不可选中数据。
            //获取下个月数据
            var nextMonth = moment(currentDate).add(1, 'month').format("YYYY-MM");
            var nexDay = 42 - daysInMonth - startOfDay + 1;
            for (var i = 1; i <= nexDay; i++) {
                if (i < 10) {
                    var nex = '0' + i
                } else {
                    var nex = i
                }
                var nexList = this.nextMonth + '-' + nex;
                var obj = {
                    time: nexList,
                    day: i,
                    month: 'next',
                }
                this.monthList.push(obj)
            }
            // this.loadData()
        },
        //上一个月
        up() {
            this.curDate = moment(this.curDate).subtract(1, 'month').format("YYYY-MM");
            this.init()
        },
        //下一个月
        next() {
            this.curDate = moment(this.curDate).add(1, 'month').format("YYYY-MM");
            this.init()
        },
        //选中时间
        checkedDay(time) {
            if (time.month == 'current') {
                this.curDateHoverMonth = time.time;
                this.onCalendarSelect();
            }
        },
        //获取这个月的数据
        loadData() {
            var self_ = this;
            var calendarKey = this.config.calendarKey;
            var start = "";
            var end = "";
            //获取当前月第一天0时0分0秒
            start = moment(this.curDate).startOf('month').format('YYYY-MM-DD');
            //获取当前月最后一天0时0分0秒
            end = moment(this.curDate).endOf('month').format('YYYY-MM-DD');
            var parameter = {months: [start, end]};
            var params = {params: JSON.stringify(parameter)};
            MainLayoutApi.getDataByKey(calendarKey, params).then(res => {
                if (res.success && res.data && res.data.calendarView) {
                    this.calendarView = res.data.calendarView;
                    this.jsScript = res.data.calendarView.jsScript;
                    this.idField = this.calendarView.columnConf.idField;
                    this.allMonthData = res.data.calendarData.monthData;
                    var optionsButtons = res.data.calendarView.buttonConf;
                    this.buttonsRow = optionsButtons.filter(ther => {
                        if (ther.btnType == 'row') {
                            return ther
                        }
                    })
                    this.buttonsHead = optionsButtons.filter(ther => {
                        if (ther.btnType == 'head') {
                            return ther
                        }
                    })
                    this.initCalendarData(res.data.calendarData.monthData);
                    this.onCalendarSelect();
                } else {
                    throw new Error( this.i18n('noKey','未查询到key为') + calendarKey + this.i18n('calView','的日历视图!'))
                }
            })
        },
        //获取当天的数据
        onCalendarSelect() {
            this.dayData = [];
            if (!this.calendarView.columnConf) {
                return
            }
            if (this.calendarView.columnConf.timeQuantum) {
                //跨天
                this.monthData.forEach(item => {
                    if (moment(item.start.split(' ')[0]).valueOf() <= moment(this.curDateHoverMonth).valueOf() && moment(this.curDateHoverMonth).valueOf() <= moment(item.end.split(' ')[0]).valueOf()) {
                        var data = this.getDayData(item);
                        this.dayData.push(data);
                    }
                });
            } else {
                //不跨天
                this.monthData.forEach(item => {
                    if (item.start.includes(this.curDateHoverMonth)) {
                        var data = this.getDayData(item);
                        this.dayData.push(data);
                    }
                });
            }
        },
        initCalendarData(data) {
            if (data) {
                this.monthData = [];
                var timeFields = [];
                if (this.calendarView.columnConf.timeFields) {
                    timeFields = this.calendarView.columnConf.timeFields
                } else {
                    timeFields = [{
                        startField: this.calendarView.columnConf.startField,
                        endField: this.calendarView.columnConf.endField,
                        background: "",
                    }];
                }
                for (let i = 0; i < timeFields.length; i++) {
                    var timeField = timeFields[i];
                    for (let j = 0; j < data.length; j++) {
                        var item = data[j];
                        var obj = {
                            pkId: item[this.idField],
                            title: item.monthTitle,
                            start: item[timeField.startField],
                            cssClass: ["family", "career"],
                            YOUR_DATA: {},
                            background: timeField.background
                        }
                        if (this.calendarView.columnConf.timeQuantum) {
                            obj.end = item[timeField.endField]
                        }
                        if (obj.start) {
                            this.monthData.push(obj);
                        }
                    }
                }
            }
        },
        //判断当天是否有数据
        getCalendarDayListData(value) {
            var show = false
            if (!this.calendarView.columnConf) {
                return false
            }
            if (this.calendarView.columnConf.timeQuantum) {
                //跨天
                var time = value.time;
                this.monthData.forEach(item => {
                    if (moment(item.start.split(' ')[0]).valueOf() <= moment(time).valueOf() && moment(time).valueOf() <= moment(item.end.split(' ')[0]).valueOf()) {
                        show = true
                    }
                });

            } else {
                //不跨天
                var time = value.time;
                this.monthData.forEach(item => {
                    if (item.start.includes(time)) {
                        show = true
                    }
                });
            }
            return show
        },
        getDayData(record) {
            var dayColumns = this.config.daySetting.dayColumns;
            if (!dayColumns || dayColumns.length == 0) {
                return record;
            }
            for (let i = 0; i < this.allMonthData.length; i++) {
                var data = this.allMonthData[i];
                if (data[this.calendarView.columnConf.idField] == record.pkId) {
                    for (let j = 0; j < dayColumns.length; j++) {
                        record[dayColumns[j].key] = data[dayColumns[j].key];
                    }
                    break;
                }
            }
            return record;
        },
        calendarButtom(obj) {
            this.$refs.popup.open('bottom')
            this.curRow = obj

        },
        handButtonClick(btn) {
            this[btn.btnClick](this.curRow);
        },
        //新增
        onAdd(row) {
            this.close()
            let params = {
                action: "edit",
            };
            params.alias = this.calendarView.formAlias;
            if (this.calendarView.formAddAlias) {
                params.alias = this.calendarView.formAddAlias;
            }
            uni.navigateTo({
                url: '/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent?params=' + JSON.stringify(params)
            })
        },
        //编辑
        onEdit(row) {
            this.close()
            let pkId = row.pkId;
            let params = {
                pk: pkId,
                action: "edit"
            }
            params.alias = this.calendarView.formAlias;
            uni.navigateTo({
                url: '/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent?params=' + JSON.stringify(params)
            })
        },
        //明细
        onDetail(row) {
            this.close()
            let pkId = row.pkId;
            let params = {
                pk: pkId,
                action: "detail"
            }
            params.alias = this.calendarView.formAlias;
            uni.navigateTo({
                url: '/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent?params=' + JSON.stringify(params)
            })
        },
        //删除
        onRemove(row) {
            this.close()
            let self_ = this;
            uni.showModal({
                title:this.i18n('tips','提示'),
                content:this.i18n('sureDelete','确认删除该记录?'),
                success: function (res) {
                    if (res.confirm) {
                        let params = {
                            alias: self_.calendarView.formAlias,
                            id: row.pkId
                        }
                        FormBoListApi.formSolutionRemoveById(params).then(res => {
                            if (res.success) {
                                uni.showToast({
                                    title: res.message,
                                    duration: 1500,
                                    icon: 'none'
                                });
                                self_.loadData()
                            }
                        })
                    } else if (res.cancel) {
                    }
                }
            });
        },
        today() {
            this.curDate = moment().format("YYYY-MM");
            this.curDateMonth = moment().format("YYYY-MM-DD");
            this.curDateHoverMonth = moment().format("YYYY-MM-DD")
            this.init();
        },
        close() {
            this.$refs.popup.close()
        },
        addRow() {
            this.$refs.popupRow.open('bottom')
        }
    },
}
</script>

<style scoped>
.calendar-common-img {
    background-color: rgb(0, 122, 255);
}

.today {
    padding: 0rem 0.5rem;
    border-radius: 5px;
    font-size: 0.7rem;
    width: 3rem;
    height: 1.5rem;
    margin-top: .2rem;
    text-align: center;
    line-height: 1.5rem;
    border: solid 1px #ffffff;
    color: white;
    margin-left: 2.5rem;
}

.mask-bottom {
    width: 100%;
    background-color: #fff;
    text-align: center;
    position: fixed;
    left: 0px;
    bottom: 0px;
}

.mask-bottom li {
    font-size: 1rem !important;
    line-height: 2.5rem;
    height: 2.5rem;

}

.calend-span {
    display: block;
    margin: auto;
    width: 4px;
    border-radius: 4px;
    height: 4px;
    background: white;
    margin-top: -8px;
}

.calend-span-hover {
    background: #3478f3 !important;
}

.schedule-common-list-node {
    position: absolute;
    left: -0.4rem;
    top: 0rem;
    height: 0.8rem;
    width: 0.8rem;
    background-color: #3478f3;
    box-shadow: 0.09rem 0.12rem 0.47rem 0rem rgba(52, 120, 243, 0.3);
    border-radius: 50%;
}

.schedule-common-list-node span {
    display: block;
    width: 0.2rem;
    height: 0.2rem;
    border-radius: 50%;
    background: white;
    margin: 0.3rem auto;
}

.schedule-common-list:last-child {
    border: none !important;
}

.schedule-common-list-common {
    padding: 0.8rem;
    border-radius: 0.53rem;
    background: white;
    margin-top: 0.6rem;
    box-shadow: 0.06rem 0.17rem 1.18rem 0rem rgba(106, 130, 173, 0.13);
}

.schedule-common-list-time {
    font-size: 0.7rem;
    color: #777777;
    line-height: 0.5rem;
}

.schedule-common-list {
    border-left: 1px solid rgba(52, 120, 243, 0.2);
    width: calc(100% - 1rem);
    margin: auto;
    padding-left: 1.18rem;
    position: relative;
    padding-bottom: 1rem;
}

.schedule-common-head-button-day {
    border: 0.5rem solid white;
    position: absolute;
    top: -1rem;
    right: 0.5rem;
    width: 3.5rem;
    height: 3.5rem;
    border-radius: 50%;
}

.schedule-common-head-button {
    width: 100%;
    height: 100%;
    background-image: linear-gradient(0deg,
    #3478f3 0%,
    #5c96ff 100%);
    box-shadow: 0rem 0.38rem 0.85rem 0rem rgba(27, 80, 175, 0.24);
    border-radius: 50%;
    text-align: center;
    line-height: 3.5rem;
    z-index: 99;
}

.schedule-common-head-button i {
    color: white;
    font-size: 2rem;
}

.schedule-common-head {
    color: #333333;
    font-size: 0.9rem;
    line-height: .5rem;
}

.schedule-common {
    position: relative;
    padding: 1rem;
    background: white;
}

.day-forbid {
    color: rgba(255, 255, 255, 0.4) !important;
}

.calendar-time-day-li {
    width: 2rem;
    height: 2rem;
    line-height: 2rem;
    text-align: center;
    margin: auto;
    color: white;
}

.calendar-time-day-li-hover {
    background: #ffffff;
    box-shadow: 0.09rem 0.12rem 0.47rem 0rem rgba(52, 120, 243, 0.3);
    border-radius: 0.47rem;
    color: #3478f3 !important;
}

.calendar-time-day-li-hover-day {
    border: 1px solid white;
    border-radius: 0.47rem;
}

.calendar-time-day {
    display: flex;
    width: 100%;
    flex-wrap: wrap;
}

.calendar-time-day li {
    flex: 0 0 14.28%;
    text-align: center;
    height: 2rem;
    margin: .25rem 0rem;
}

.calendar-time-head {
    display: flex;
    height: 2rem;
}

.calendar-time-head li {
    flex: 1;
    text-align: center;
    font-size: 1rem;
    color: white;
    line-height: 2rem;
}

.calendar-common {
    width: 100%;
    height: 22rem;
    overflow: hidden;
    background-image: url("@/static/schedule.png");
    background-size: 100% 100%;
}

.calendar-common-head {
    display: flex;
    overflow: hidden;
    line-height: 2rem;
    margin: 1rem;
}

.calendar-common-head-day {
    flex: 1;
    font-size: 1.1rem;
    color: white;
    text-align: center;
    font-weight: bold;
}

.calendar-common-head-icon {
    height: 2rem;
    width: 2rem;
    border-radius: 50%;
    text-align: center;
    line-height: 2rem;
    color: #ffffff;
}
</style>
